<template>
  <div class="user-table-select">
    <el-dialog
      :title="title"
      width="420px"
      :visible.sync="visible"
      :before-close="doCancel"
    >
      <div class="qrcode-bar">
        <div class="-inner">
          <div class="-login">
            <a class="-image"><img :src="this.qrcode"/></a>
          </div>
          <div class="-ops">
            <a @click.stop="doDownload">下载</a>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Fetch from "@/api/fetch";

export default {
  name: "qrcode",
  data() {
    return {
      qrcode: ""
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: ,
    api: 
  },
  watch: {
    visible: function() {
      if (this.visible) {
        this.loadQrCode();
      }
    }
  },
  methods: {
    loadQrCode: function() {
      Fetch({
        url: this.api,
        method: "get"
      }).then(res => {
        this.qrcode = res.obj.qrcode;
      });
    },
    doCancel: function() {
      this.$emit("update:visible", false);
    },
    doDownload: function() {
      var data = this.qrcode;
      var fileName = this.title + ".png";
      let url = window.URL.createObjectURL(this.base642Blob(data));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", decodeURI(fileName));
      document.body.appendChild(link);
      link.click();
    },
    base642Blob: function(code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    }
  }
};
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@require "../../common/stylus/variable.styl"
.qrcode-bar {
  text-align center;
  .-login {
    position relative;
    .-image {
      display block;
    }
  }
  .-ops {
    a {
      color $color-primary;
      cursor pointer;
    }
  }
}
</style>
